package test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main2 {

	public static void main(String[] args) {
		String str_send = "Hello UDPserver";  
        byte[] buf = new byte[1024];
        SocketAddress address = null;
        DatagramSocket ds = null;
        //客户端在9000端口监听接收到的数据  
		try {
			ds = new DatagramSocket(2617);
			address = new InetSocketAddress("1.71.119.169", 2617);
			ds.setSoTimeout(5000);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //定义用来发送数据的DatagramPacket实例  
        DatagramPacket dp_send= new DatagramPacket(str_send.getBytes(),str_send.length(),address);
        //定义用来接收数据的DatagramPacket实例 
        DatagramPacket dp_receive = new DatagramPacket(buf, 1024);  
        int tries = 0;                         //重发数据的次数  
        boolean receivedResponse = false;     //是否接收到数据的标志位  
        //直到接收到数据，或者重发次数达到预定值，则退出循环  
        while(!receivedResponse && tries<5){ 
            //发送数据  
            try {
				ds.send(dp_send);
				ds.receive(dp_receive);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}  
			//如果接收到的数据不是来自目标地址，则抛出异常  
			if(!dp_receive.getAddress().equals(address)){  
			    try {
					throw new IOException("Received packet from an umknown source");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
			}  
			//如果接收到数据。则将receivedResponse标志位改为true，从而退出循环  
			receivedResponse = true;  
        }  
        if(receivedResponse){  
            //如果收到数据，则打印出来
            System.out.println("client received data from server：");  
            String str_receive = new String(dp_receive.getData(),0,dp_receive.getLength()) +
                    " from " + dp_receive.getAddress().getHostAddress() + ":" + dp_receive.getPort();
            System.out.println(str_receive);  
            //由于dp_receive在接收了数据之后，其内部消息长度值会变为实际接收的消息的字节数，  
            //所以这里要将dp_receive的内部消息长度重新置为1024  
            dp_receive.setLength(1024);     
        }else{  
            //如果重发MAXNUM次数据后，仍未获得服务器发送回来的数据，则打印如下信息  
            System.out.println("No response -- give up.");
        }  
        ds.close();  
    }    
}
